package com.stu.wgt.test.controller;


import com.stu.wgt.test.bean.Images;
import com.stu.wgt.test.result.R;
import com.stu.wgt.test.service.ImagesService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.util.List;

/**
 * <p>
 * 前端控制器
 * </p>
 *
 * @author wgt
 * @since 2024-03-04
 */
@RestController
@RequestMapping("/images")
public class ImagesController {
    @Autowired
    ImagesService imagesService;

    @RequestMapping("/select")
    public R select() {
        try {
            List<Images> imagesList = imagesService.select();
            return R.ok().data("images", imagesList);
        } catch (Exception e) {
            e.printStackTrace();
            return R.error();
        }
    }

    @PostMapping("/add")
    public R addImage(@RequestBody Images images) {
        try {
            imagesService.insert(images);
            return R.ok();
        } catch (Exception e) {
            e.printStackTrace();
            return R.error();
        }
    }

    @DeleteMapping("/delete/{id}")
    public R delete(@PathVariable("id") int id) {
        try {
            imagesService.delete(id);
            return R.ok().data("msg", "删除图片成功");
        } catch (Exception e) {
            e.printStackTrace();
            return R.error().data("msg", "删除图片失败,请提供正确的ID");
        }
    }

    /**
     * 轮播图图片上传
     *
     * @param file
     * @return
     */
    @PostMapping("/upload")
    public R handleFileUpload(@RequestParam("file") MultipartFile file) {
        System.out.println("轮播图上传");
        try {
            String uploadDir = "E:/桌面/毕业设计/代码/后端/src/main/resources/static/image/slider/";
            String originalFileName = file.getOriginalFilename();

            // 处理中文文件名编码
            String tmpPath = new String(originalFileName.getBytes("UTF-8"), "ISO-8859-1");

            File dest = new File(uploadDir + tmpPath);
            file.transferTo(dest);
            //String uuid = UUID.randomUUID().toString().replace("-", "");//UUID生成不重复的一串数字
            String url = "http://127.0.0.1:8888/image/slider/" + tmpPath;
            return R.ok().data("path", tmpPath).data("url", url);
        } catch (Exception e) {
            e.printStackTrace();
            return R.error();
        }
    }

}

